package org.steven.crm.core.utils.wx;

import cn.hutool.core.codec.Base64;
import org.steven.crm.core.utils.http.HttpConnectionManager;
import org.apache.http.HttpResponse;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.util.EntityUtils;
import org.apache.log4j.Logger;
import org.jdom.Document;
import org.jdom.Element;
import org.jdom.JDOMException;
import org.jdom.input.SAXBuilder;

import javax.crypto.Cipher;
import javax.crypto.spec.IvParameterSpec;
import javax.crypto.spec.SecretKeySpec;
import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.security.spec.AlgorithmParameterSpec;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;

public class WeixinUtil {
	private static Logger logger = Logger.getLogger(WeixinUtil.class);
	
	public static String getPayNo(String url, String xmlParam) {
		CloseableHttpClient client = null;
		String prepay_id = "";
		try { 
			client = HttpConnectionManager.getInstance().getHttpClient();
			HttpPost httpost = new HttpPost(url);
			httpost.setEntity(new StringEntity(xmlParam, "UTF-8"));
			HttpResponse response = client.execute(httpost);
			String jsonStr = EntityUtils.toString(response.getEntity(), "UTF-8");
			logger.info("jsonStr:" + jsonStr);

			if (jsonStr.indexOf("FAIL") != -1) {
				return prepay_id;
			}
			Map<String, String> map = doXMLParse(jsonStr);
			prepay_id = map.get("prepay_id");
		} catch (Exception e) {
			logger.error("getPayNo:", e);
		}
		
		return prepay_id;
	}

	/**
	 * 获取预支付订单
	 * @param url
	 * @param xmlParam
	 * @return
	 */
	public static Map<String, String> getWxResultMap(String url, String xmlParam) {
		CloseableHttpClient client = null;
		Map<String, String> map = new HashMap<String, String>();
		try {
			client = HttpConnectionManager.getInstance().getHttpClient();
			HttpPost httpost = new HttpPost(url);
			httpost.setEntity(new StringEntity(xmlParam, "UTF-8"));
			HttpResponse response = client.execute(httpost);
			String jsonStr = EntityUtils.toString(response.getEntity(), "UTF-8");
			logger.info("jsonStr:" + jsonStr);

			if (jsonStr.indexOf("FAIL") != -1) {
				return null;
			}
			map = doXMLParse(jsonStr);
		} catch (Exception e) {
			logger.error("getPayNo:", e);
		}
		return map;
	}
	
	/**
	 * 解析xml,返回第一级元素键值对。如果第一级元素有子节点，则此节点的值是子节点的xml数据。
	 * @param strxml
	 * @return
	 * @throws JDOMException
	 * @throws IOException
	 */
	public static Map<String, String> doXMLParse(String strxml) throws Exception {
		if (null == strxml || "".equals(strxml)) {
			return null;
		}

		Map<String, String> m = new HashMap();
		InputStream in = String2Inputstream(strxml);
		SAXBuilder builder = new SAXBuilder();
		Document doc = builder.build(in);
		Element root = doc.getRootElement();
		List list = root.getChildren();
		Iterator it = list.iterator();
		while (it.hasNext()) {
			Element e = (Element) it.next();
			String k = e.getName();
			String v = "";
			List children = e.getChildren();
			if (children.isEmpty()) {
				v = e.getTextNormalize();
			} else {
				v = getChildrenText(children);
			}

			m.put(k, v);
		}

		in.close();
		return m;
	}

	/**
	 * 解密微信加密数据
	 * @param encrypdata
	 * @param ivdata
	 * @param sessionkey
	 * @return
	 * @throws Exception
	 */
	public static String deciphering(String encrypdata, String ivdata, String sessionkey) throws Exception {
		byte[] encrypData = Base64.decode(encrypdata);
		byte[] ivData = Base64.decode(ivdata);
		byte[] sessionKey = Base64.decode(sessionkey);
		String str = decrypt(sessionKey,ivData,encrypData);
		return str;
	}

	private static String decrypt(byte[] key, byte[] iv, byte[] encData) throws Exception {
		AlgorithmParameterSpec ivSpec = new IvParameterSpec(iv);
		Cipher cipher = Cipher.getInstance("AES/CBC/PKCS5Padding");
		SecretKeySpec keySpec = new SecretKeySpec(key, "AES");
		cipher.init(Cipher.DECRYPT_MODE, keySpec, ivSpec);
		return new String(cipher.doFinal(encData),"UTF-8");
	}

	/**
	 * 获取子结点的xml
	 * @param children
	 * @return String
	 */
	private static String getChildrenText(List children) {
		StringBuffer sb = new StringBuffer();
		if (!children.isEmpty()) {
			Iterator it = children.iterator();
			while (it.hasNext()) {
				Element e = (Element) it.next();
				String name = e.getName();
				String value = e.getTextNormalize();
				List list = e.getChildren();
				sb.append("<" + name + ">");
				if (!list.isEmpty()) {
					sb.append(getChildrenText(list));
				}
				sb.append(value);
				sb.append("</" + name + ">");
			}
		}

		return sb.toString();
	}

	private static InputStream String2Inputstream(String str) {
		return new ByteArrayInputStream(str.getBytes());
	}

}